function Camera(x, y, z, fov, w, h) {
    this.x = x;        // 空间中的 x坐标
    this.y = y;        // 空间中的 y坐标
    this.z = z;        // 空间中的 z坐标
    this.fov = fov;    // 以 x轴为 [0, 0] y轴为 [90, 0] z轴为 [0, 90] 的 三维角度
    this.fov[0] = fov[0] % 360 + (fov[0] < 0 ? 360 : 0);
    this.fov[0] -= (this.fov[0] >= 180 ? 360 : 0);
    this.fov[1] = fov[1] % 360 + (fov[1] <= -180 ? 360 : 0);
    this.w = w;
    this.h = h;
    this.getPositionAndOrientation = () => {
        return {
            position: [this.x, this.y, this.z],
            fov: this.fov,
            width: this.w,
            height: this.h
        }
    }
    this.setPositionAndOrientation = (x, y, z, fov) => {
        this.x = x;
        this.y = y;
        this.z = z;
        this.fov = fov;
    }
    this.resetPositionAndOrientation = () => {
        this.x = 0;
        this.y = 0;
        this.z = 0;
        this.fov = [0, 0];
    }
}

// 创建 3d 场景的函数
function World(canvas) {
    let canvasWidth = parseInt(canvas.getAttribute('width'));
    let canvasHeight = parseInt(canvas.getAttribute('height'));
    this.canvas = canvas;
    this.camera = new Camera(300, 300, 300, [-135, -35], canvasWidth, canvasHeight);
    this.webwork = new Worker('./webwork/webwork.js');
    // 将 3d 模型 渲染到 场景的方法
    this.createModel = (model) => {
        // 获取最新的相机位置与朝向
        let cameraInfo = this.getCameraPositionAndOrientation();
        // 连接 webwork 进行计算 视野中的内容 并自动渲染
        this.sendWebWork(cameraInfo, model);
    }
    this.getCameraPositionAndOrientation = () => {
        return this.camera.getPositionAndOrientation();
    }

    // 将 3d 模型数据 发送给 webwork 进行计算
    this.sendWebWork = (cameraInfo, model) => {
        let sendData = {cameraInfo, model};
        this.webwork.postMessage(sendData);
    }

    // 设置 webwork监听器
    this.webwork.addEventListener('message', (e) => {
        let planeList = e.data.planeList;
        this.showModel(planeList);
    });

    // 真正进行模型绘制的方法
    this.showModel = (drawList) => {
        console.log(drawList);
        let ctx = this.canvas.getContext('2d');
        ctx.clearRect(0, 0, canvasWidth, canvasHeight);
        // 绘制顶点为 [item[0][0], item[0][1]] [item[1][0], item[1][1]] [item[2][0], item[2][1]] 填充颜色为 item[3] 的闭合多边形
        // for (let i = 0; i < drawList.length; i++) {
        //     let item = drawList[i];
        // }
        drawList.forEach(item => {
            this.drawPolygon(ctx, item[0], item[1], item[2], item[3]);
            console.log('item绘制完毕', item);
        });
    }

    // 绘制一个平面的方法
    this.drawPolygon = (ctx, p1, p2, p3, color) => {
        ctx.fillStyle = color;
        ctx.beginPath();
        ctx.moveTo(p1[0], p1[1]);
        ctx.lineTo(p2[0], p2[1]);
        ctx.lineTo(p3[0], p3[1]);
        ctx.closePath();
        ctx.fill();
    }
}

